package src;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class DataManager {
    private static final String DATA_FOLDER = "data/";
    private static final String USERS_FILE = DATA_FOLDER + "users.txt";
    private static final String MOVIES_FILE = DATA_FOLDER + "movies.txt";
    private static final String SCREENINGS_FILE = DATA_FOLDER + "screenings.txt";
    private static final String ORDERS_FILE = DATA_FOLDER + "orders.txt";
    private static final String LOGS_FILE = DATA_FOLDER + "system_log.txt";
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final String SNACKS_FILE = DATA_FOLDER + "snacks.txt";  // 新增零食数据文件路径

    public static void createDataFolder() {
        File dataFolder = new File(DATA_FOLDER);
        if (!dataFolder.exists()) {
            if (dataFolder.mkdirs()) {
                System.out.println("数据文件夹已创建: " + DATA_FOLDER);
            } else {
                System.err.println("无法创建数据文件夹: " + DATA_FOLDER);
            }
        }
    }
    // 加载用户数据
    public static List<User> loadUsers() {
        List<User> users = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try (BufferedReader reader = new BufferedReader(new FileReader(USERS_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                // 新增：检查字段数量是否符合要求（至少7个字段）
                if (parts.length < 7) {
                    System.err.println("无效的用户数据行: " + line);
                    continue;
                }
                if (parts.length >= 6) {
                    String userId = parts[0];
                    String username = parts[1];
                    String passwordHash = parts[2];
                    String role = parts[3];
                    boolean mustChangePassword = Boolean.parseBoolean(parts[4]);
                    LocalDateTime registrationTime = LocalDateTime.parse(parts[5], formatter);
                    String phoneNumber = parts[6];

                    User user = new User(userId, username, passwordHash, role, registrationTime, phoneNumber);
                    user.setMustChangePassword(mustChangePassword);
                    users.add(user);
                }
            }
        } catch (FileNotFoundException e) {
            // 文件不存在，创建默认管理员账户
            users.add(new User("admin001", "admin", MD5Util.encrypt("ynuinfo#777"), "管理员", LocalDateTime.now(), "1234567890"));
        } catch (IOException e) {
            System.err.println("加载用户数据时出错: " + e.getMessage());
        }
        return users;
    }

    // 保存用户数据
    public static void saveUsers(List<User> users) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(USERS_FILE))) {
            for (User user : users) {
                writer.write(user.getUserId() + "," +
                        user.getUsername() + "," +
                        user.getPasswordHash() + "," +
                        user.getRole() + "," +
                        user.mustChangePassword() + "," +
                        user.getRegistrationTime().format(formatter) + "," +
                        user.getPhoneNumber());
                writer.newLine();
            }
        } catch (IOException e) {
            System.err.println("保存用户数据时出错: " + e.getMessage());
        }
    }

    // 加载电影数据
    public static List<Movie> loadMovies() {
        List<Movie> movies = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(MOVIES_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 6) {
                    String title = parts[0];
                    String director = parts[1];
                    String actors = parts[2];
                    String synopsis = parts[3];
                    int duration = Integer.parseInt(parts[4]);
                    double rating = Double.parseDouble(parts[5]);
                    movies.add(new Movie(title, director, actors, synopsis, duration, rating));
                }
            }
        } catch (FileNotFoundException e) {
            movies.add(new Movie("复仇者联盟4", "安东尼·罗素", "小罗伯特·唐尼", "复仇者联盟与灭霸的最终决战", 181, 8.5));
            movies.add(new Movie("泰坦尼克号", "詹姆斯·卡梅隆", "莱昂纳多·迪卡普里奥", "一段跨越阶层的爱情故事", 194, 9.0));
        } catch (IOException e) {
            System.err.println("加载电影数据时出错: " + e.getMessage());
        }
        return movies;
    }

    // 保存电影数据
    public static void saveMovies(List<Movie> movies) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(MOVIES_FILE))) {
            for (Movie movie : movies) {
                writer.write(movie.getTitle() + "," +
                        movie.getDirector() + "," +
                        movie.getActors() + "," +
                        movie.getSynopsis() + "," +
                        movie.getDuration() + "," +
                        movie.getRating());
                writer.newLine();
            }
        } catch (IOException e) {
            System.err.println("保存电影数据时出错: " + e.getMessage());
        }
    }

    // 加载场次数据
    public static List<Screening> loadScreenings(List<Movie> movies, List<ScreeningRoom> rooms) {
        List<Screening> screenings = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(SCREENINGS_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length >= 5) {
                    String movieTitle = parts[0];
                    String roomName = parts[1];
                    LocalDateTime startTime = LocalDateTime.parse(parts[2]);
                    double price = Double.parseDouble(parts[3]);

                    Movie movie = findMovieByTitle(movies, movieTitle);
                    ScreeningRoom room = findRoomByName(rooms, roomName);

                    if (movie != null && room != null) {
                        screenings.add(new Screening(movie, room, startTime, price));
                    }
                }
            }
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
            System.err.println("加载场次数据时出错: " + e.getMessage());
        }
        return screenings;
    }

    // 保存场次数据
    public static void saveScreenings(List<Screening> screenings) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(SCREENINGS_FILE))) {
            for (Screening screening : screenings) {
                writer.write(screening.getMovie().getTitle() + "," +
                        screening.getRoom().getName() + "," +
                        screening.getStartTime() + "," +
                        screening.getPrice());
                writer.newLine();
            }
        } catch (IOException e) {
            System.err.println("保存场次数据时出错: " + e.getMessage());
        }
    }

    // 加载订单数据
    public static List<Order> loadOrders() {
        List<Order> orders = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(ORDERS_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length >= 10) {
                    String orderId = parts[0];
                    String username = parts[1];
                    String movieTitle = parts[2];
                    String roomName = parts[3];
                    LocalDateTime startTime = LocalDateTime.parse(parts[4]);
                    int row = Integer.parseInt(parts[5]);
                    int seat = Integer.parseInt(parts[6]);
                    double amount = Double.parseDouble(parts[7]);
                    LocalDateTime orderTime = LocalDateTime.parse(parts[8]);
                    boolean isRefunded = Boolean.parseBoolean(parts[9]);
                    
                    Movie movie = findMovieByTitle(CinemaSystem.movies, movieTitle);
                    ScreeningRoom room = findRoomByName(CinemaSystem.rooms, roomName);
                    
                    if (movie != null && room != null) {
                        Screening screening = new Screening(movie, room, startTime, amount);
                        Order order = new Order(orderId, username, screening, row, seat, amount, orderTime);
                        
                        if (isRefunded && parts.length >= 11) {
                            LocalDateTime refundTime = LocalDateTime.parse(parts[10]);
                            double refundAmount = Double.parseDouble(parts[11]);
                            // 由于Order类的refund方法会设置当前时间，这里我们需要通过反射设置
                            try {
                                java.lang.reflect.Field refundedField = Order.class.getDeclaredField("isRefunded");
                                refundedField.setAccessible(true);
                                refundedField.set(order, true);
                                
                                java.lang.reflect.Field refundTimeField = Order.class.getDeclaredField("refundTime");
                                refundTimeField.setAccessible(true);
                                refundTimeField.set(order, refundTime);
                                
                                java.lang.reflect.Field refundAmountField = Order.class.getDeclaredField("refundAmount");
                                refundAmountField.setAccessible(true);
                                refundAmountField.set(order, refundAmount);
                            } catch (Exception e) {
                                System.err.println("加载退票信息时出错: " + e.getMessage());
                            }
                        }
                        
                        orders.add(order);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            // 文件不存在，无需处理
        } catch (IOException e) {
            System.err.println("加载订单数据时出错: " + e.getMessage());
        }
        return orders;
    }

    // 保存订单数据
    public static void saveOrders(List<Order> orders) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(ORDERS_FILE))) {
            for (Order order : orders) {
                writer.write(order.getOrderId() + "," +
                        order.getUsername() + "," +
                        order.getScreening().getMovie().getTitle() + "," +
                        order.getScreening().getRoom().getName() + "," +
                        order.getScreening().getStartTime() + "," +
                        order.getRow() + "," +
                        order.getSeat() + "," +
                        order.getAmount() + "," +
                        order.getOrderTime() + "," +
                        order.isRefunded() + "," +
                        (order.isRefunded() ? order.getRefundTime() : "") + "," +
                        (order.isRefunded() ? order.getRefundAmount() : ""));
                writer.newLine();
            }
        } catch (IOException e) {
            System.err.println("保存订单数据时出错: " + e.getMessage());
        }
    }

    // 从文件加载历史日志
    public static List<String> loadLogs() {
        List<String> logs = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(LOGS_FILE))) {
            String log;
            while ((log = reader.readLine()) != null) {
                logs.add(log);
            }
        } catch (FileNotFoundException e) {
            System.out.println("日志文件不存在或为空。");
        } catch (IOException e) {
            System.err.println("加载日志时出错: " + e.getMessage());
        }
        return logs;
    }

    private static Movie findMovieByTitle(List<Movie> movies, String title) {
        for (Movie movie : movies) {
            if (movie.getTitle().equals(title)) {
                return movie;
            }
        }
        return null;
    }

    public static void saveLogs(List<String>logs) {
        if (logs.isEmpty()) {
            return;
        }
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(LOGS_FILE, true))) {
            for (String log : logs) {
                writer.write(log);
                writer.newLine();
            }
        } catch (IOException e) {
            System.err.println("保存日志时出错: " + e.getMessage());
        }
    }

    private static ScreeningRoom findRoomByName(List<ScreeningRoom> rooms, String name) {
        for (ScreeningRoom room : rooms) {
            if (room.getName().equals(name)) {
                return room;
            }
        }
        return null;
    }

    // 加载零食数据（
    public static List<Snack> loadSnacks() {
        List<Snack> snacks = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(SNACKS_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                if (parts.length == 3) {
                    snacks.add(new Snack(parts[0], Double.parseDouble(parts[1]), Integer.parseInt(parts[2])));
                }
            }
        } catch (FileNotFoundException e) {
            // 文件不存在时初始化默认零食
            snacks.add(new Snack("爆米花", 25.0, 50));
            snacks.add(new Snack("可乐", 15.0, 100));
        } catch (IOException e) {
            System.err.println("加载零食数据失败: " + e.getMessage());
        }
        return snacks;
    }
    
    // 保存零食数据
    public static void saveSnacks(List<Snack> snacks) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(SNACKS_FILE))) {
            for (Snack snack : snacks) {
                writer.write(snack.getName() + "," + snack.getPrice() + "," + snack.getStock() + "\n");
            }
        } catch (IOException e) {
            System.err.println("保存零食数据失败: " + e.getMessage());
        }
    }
}